/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useState } from 'react';

type FormData = { base?: pickedFaceData };

type Params = {
  base: string;
};

function CommandBoundary({ title, onClose, props }: CurvedCmdDialogParams) {
  const [formData, setFormData] = useState<FormData>({});

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({});
      return;
    }

    const params: Params = props.params;
    const { base } = params;

    await initEditDependency([base]);

    setFormData({
      base: picker.generatePickObjByPickID(base) as pickedFaceData,
    });
  }, [props?.shape]);

  const isFormDataValid = () => {
    return formData.base != null;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await confirmCommand({
      type: 'Boundary',
      a: { base: formData.base.meshId },
    });

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, isLoading } =
    useCommand('cmd-boundary', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      base: {
        type: 'string',
        format: PickInputRJSFFormat.PickSurface,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      submitLoading={isLoading}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        base: {
          'ui:placeholder': '请输入曲面',
          'ui:autofocus': true,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
      noValidate
    />
  );
}

export const cmdBoundary: CurvedBaseCommand = {
  id: 'CommandBoundary',
  label: 'command.boundary',
  icon: 'commands/curved/boundary',
  create: (label, onClose, props) => (
    <CommandBoundary
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
